<template>
    <transition name="slide">
      <music-list :rank="true" :title="title" :bg-image="bgImage" :songs="songs"></music-list>
    </transition>
</template>

<script>
    import MusicList from 'components/music-list/music-list'
    import {mapGetters} from 'vuex';// 使用vuex获取排行榜歌曲详情的数据
    import {getMusicList} from "api/rank"; // 请求排行列表歌曲详情的api
    import {ERR_OK} from "api/config";
    import {createSong} from "common/js/song"; // 获取到的数据通过createSong转成Song的实例
    import {getMusic} from "api/singer";

    export default {
      name: "top-list",
      data () {
        return {
          songs: [],
          rank: true
        }
      },
      computed: {
        ...mapGetters([
          'topList'
        ]),
        title () {
          return this.topList.topTitle;
        },
        bgImage () {
          // 使用第一首歌曲的图片作为背景图
          if (this.songs.length) {
            return this.songs[0].image
          }
          return ''
        }
      },
      created () {
        this._getMusicList()
      },
      methods: {
        _getMusicList() {
          if(!this.topList.id) {
            this.$router.push('/rank');
            return
          }
          getMusicList(this.topList.id).then((res) => {
              if (res.code === ERR_OK) {
                this.songs = this._normalizeSongs(res.songlist)
              }
          })
        },
        _normalizeSongs(list) {
          let ret = [];
          list.forEach((item) => {
            const musicData = item.data;
            if(musicData.songid && musicData.albummid) {
              getMusic(musicData.songmid).then(res=>{
                if (res.code === ERR_OK) {
                  const svkey = res.data.items;
                  const songVkey = svkey[0].vkey;
                  const newSong = createSong(musicData,songVkey)
                  ret.push(newSong)
                }
              })
            }
          });
          return ret;
        }
      },
      components: {
          MusicList
      }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .slide-enter-active, .slide-leave-active
    transition: all 0.3s ease

  .slide-enter, .slide-leave-to
    transform: translate3d(100%, 0, 0)
</style>
